package com.baibei.ebec.user.address;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.model.AddressInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.ui.AppUI;
import com.baibei.widget.CommonRefreshLayout;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;
import com.rae.widget.RaePlaceHolderLayout;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;


/**
 * 收货地址列表
 * Created by ChenRui on 2016/8/13 0013.
 */
@Route(path = AppRouter.ROUTER_ADDRESS_LIST)
public class AddressListActivity extends BasicActivity implements AddressListContract.View {

    @BindView(R2.id.lv_address_list)
    ListView mAddressListView;

    @BindView(R2.id.placeholder)
    RaePlaceHolderLayout mHolderLayout;
    @BindView(R2.id.content_layout)
    CommonRefreshLayout mRaeFragmentLayout;

    @BindView(R2.id.btn_edit_address)
    Button mAddressButton;

    private AddressListContract.Presenter mPresenter;
    private AddressListAdapter mAdapter;

    private int mCurrentPosition; // 用户记录当前点击的
    private AddressInfo mSelectAddress;
    private boolean mIsSelectAddress;
    private boolean mAddAddressSuccess; // 添加地址成功


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_list);

        mIsSelectAddress = getIntent().getBooleanExtra("isSelectAddress", false);
        mSelectAddress = getIntent().getParcelableExtra("data");

        mAdapter = new AddressListAdapter(this);
        mPresenter = inject(AddressListContract.Presenter.class);
        mAddressListView.setAdapter(mAdapter);

//        mAdapter.registerDataSetObserver(new DataSetObserver() {
//            @Override
//            public void onChanged() {
//                super.onChanged();
//                mRaeFragmentLayout.refreshComplete();
//                if (mAdapter.getCount() > 0) {
//                    mHolderLayout.dismiss();
//                } else {
//                    mHolderLayout.onEmpty();
//                }
//            }
//        });

        mRaeFragmentLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mAdapter.clear();
                mPresenter.start();
            }
        });
    }

    @Override
    public IPresenter getBasicPresenter() {
        return mPresenter;
    }

    @OnClick(R2.id.btn_edit_address)
    public void jumpToEditAddress(View view) {
        if (SessionManager.getDefault().isLogin()) {
            AppRouter.routeToEditAddress(this, null, mAdapter.getCount() <= 0);
        } else {
            AppRouter.routeToLogin(this);
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 添加地址成功
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            mAddAddressSuccess = true;
        }
        if (resultCode == RESULT_OK) {
            mPresenter.start();
        }
    }


    private void setResultSuccess(AddressInfo item) {
        Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_INTENT, item);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @Override
    public void onLoadAddress(List<AddressInfo> data) {
        mHolderLayout.dismiss();
        mRaeFragmentLayout.refreshComplete();
        mAddressListView.setAdapter(mAdapter);
        mAdapter.clear();
        mAdapter.addAll(data);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onEmptyAddress(String msg) {
        mRaeFragmentLayout.refreshComplete();
        mAddressListView.setAdapter(null);
        if (!TextUtils.isEmpty(msg))
            mHolderLayout.setText(msg);
        mHolderLayout.onEmpty();
    }

    @Override
    public void onUpdateAddressSuccess(String msg) {
        if (mSelectAddress != null && mIsSelectAddress) {
            setResultSuccess(mSelectAddress);
            return;
        }

        AppUI.success(getContext(), msg);
        mPresenter.start(); // 重新加载数据
    }

    @Override
    public void onUpdateAddressFailed(String msg) {
        AppUI.failed(getContext(), msg);
        mPresenter.start(); // 重新加载数据
    }

    @Override
    public void onDeleteAddressSuccess(String msg) {
        AppUI.success(getContext(), msg);
        mAdapter.remove(mCurrentPosition);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDeleteAddressFailed(String msg) {
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void onNotLogin() {
        mHolderLayout.onEmpty();
        mHolderLayout.setText(getString(R.string.text_login_expired));
        mAddressButton.setText(R.string.login);
    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void showLoading() {
        AppUI.loading(this, "正在操作");
    }

    class AddressListAdapter extends ArrayAdapter<AddressInfo> implements AdapterView.OnItemClickListener {


        public AddressListAdapter(Context context) {
            super(context, 0);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final AddressInfo m = getItem(position);
            AddressListAdapterViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_address_info, null, false);
                holder = new AddressListAdapterViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (AddressListAdapterViewHolder) convertView.getTag();
            }

            onInitCommonModeView(m, holder, position);
            if (mIsSelectAddress) {
                onInitSelectModeView(m, holder, convertView, position);
            } else {
                onInitNormalModeView(m, holder, position);
            }
            return convertView;
        }

        // 共同模式
        private void onInitCommonModeView(final AddressInfo m, AddressListAdapterViewHolder holder, final int position) {
            holder.mNameView.setText(m.getReceiver());
            holder.mPhoneView.setText(Rx.blockingPhone(m.getMobile()));
            holder.mDetailView.setText(m.getFullAddress());

            holder.mAddressDefaultView.setChecked(m.isDefault()); // 是否为默认地址
            holder.mAddressDefaultView.setEnabled(!m.isDefault());             // 如果是默认的就不能点

            // 编辑地址
            holder.mEditView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AppRouter.routeToEditAddress(AddressListActivity.this, m, false);
                }
            });
            // 删除地址
            holder.mDelView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mCurrentPosition = position;
                    showDeleteDialog(m);
                }
            });
        }

        // 正常模式
        private void onInitNormalModeView(final AddressInfo m, AddressListAdapterViewHolder holder, final int position) {
            holder.mDividerView.setVisibility(View.VISIBLE);
            holder.mEditView.setVisibility(View.VISIBLE);
            holder.mDelView.setVisibility(View.VISIBLE);
            holder.mAddressDefaultView.setVisibility(View.VISIBLE);


            // 设置默认地址
            holder.mAddressDefaultView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CheckBox checkBox = (CheckBox) view;
                    mCurrentPosition = position;
                    m.setDefault(checkBox.isChecked());
                    mPresenter.updateDefaultAddress(m.getId());
                }
            });
        }

        // 选择模式
        private void onInitSelectModeView(AddressInfo m, AddressListAdapterViewHolder holder, View convertView, final int position) {
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClick(null, null, position, 0);
                }
            });

//            holder.mDefaultTextView.setVisibility(m.isDefault() ? View.VISIBLE : View.GONE);

            // 当前选择的地址
            if (m.isDefault()) {
                holder.mAddressDefaultView.setVisibility(View.VISIBLE);
            } else {
                holder.mAddressDefaultView.setVisibility(View.GONE);
            }

        }


        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int currentPosition, long l) {
            // 设置默认地址
            mSelectAddress = getItem(currentPosition);
            if (mSelectAddress == null) {
                return;
            }

            Intent intent = new Intent();
            intent.putExtra("data", mSelectAddress);
            setResult(RESULT_OK, intent);
            finish();
        }

        void remove(int currentPosition) {
            remove(getItem(currentPosition));
        }
    }

    /**
     * 是否删除地址弹窗
     *
     * @param m m
     */
    private void showDeleteDialog(final AddressInfo m) {
        new DialogBuilder(getContext()).setMessage(getString(R.string.if_delete_address)).positiveButtonClickListener(new IAppDialogClickListener() {
            @Override
            public void onClick(IAppDialog iAppDialog, int i) {
                iAppDialog.dismiss();
                mPresenter.deleteAddress(m.getId());
            }
        }).negativeButtonClickListener(new IAppDialogClickListener() {
            @Override
            public void onClick(IAppDialog iAppDialog, int i) {
                iAppDialog.dismiss();
            }
        }).show();
    }

    private class AddressListAdapterViewHolder {

        private final TextView mNameView;
        private final TextView mPhoneView;
        private final TextView mDetailView;
        private final CheckBox mAddressDefaultView;
        private final TextView mEditView;
        private final TextView mDelView;
        private final View mDividerView;
//        private final View mDefaultTextView;

        AddressListAdapterViewHolder(View convertView) {
            mNameView = (TextView) convertView.findViewById(R.id.tv_address_info_name);
            mPhoneView = (TextView) convertView.findViewById(R.id.tv_address_info_phone);
            mDetailView = (TextView) convertView.findViewById(R.id.tv_address_info_detail);
            mDividerView = convertView.findViewById(R.id.view_divider_address_info);
//            mDefaultTextView = convertView.findViewById(R.id.tv_address_info_default);

            mAddressDefaultView = (CheckBox) convertView.findViewById(R.id.cb_address_info_default);
            mEditView = (TextView) convertView.findViewById(R.id.tv_address_info_edit);
            mDelView = (TextView) convertView.findViewById(R.id.tv_address_info_del);
        }
    }
}
